package com.zjsru.oneDay202205;

/**
 * @Author: likew
 * @Date: 2022/5/29
 * 验证IP地址
 *
 * 输入：queryIP = "172.16.254.1"
 * 输出："IPv4"
 * 解释：有效的 IPv4 地址，返回 "IPv4"
 *
 * 输入：queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334"
 * 输出："IPv6"
 * 解释：有效的 IPv6 地址，返回 "IPv6"
 *
 * 输入：queryIP = "256.256.256.256"
 * 输出："Neither"
 * 解释：既不是 IPv4 地址，又不是 IPv6 地址
 */
public class validIPAddress {
    public String validIPAddress(String queryIP) {
        if (queryIP.indexOf(".") >= 0 && this.checkIpv4(queryIP)) {
            return "IPv4";
        }
        if (queryIP.indexOf(":") >= 0 && this.checkIpv6(queryIP)) {
            return "IPv6";
        }
        return "Neither";
    }
    
    private boolean checkIpv4(String ip){
        int n = ip.length(), cnt = 0;
        char[] cs = ip.toCharArray();
        for (int i = 0; i < n && cnt  <= 3;) {
            int j = i,x=0;
            while(j < n && cs[j] >= '0' && cs[j] <= '9' && x<= 255){
                x = x* 10 + (cs[j++] - '0');
            }
            if (i == j) {
                return false;
            }
            if ((j - i > 1 && cs[i] == '0') || (x > 255)) {
                return false;
            }
            i = j + 1;
            if (j == n) {
                continue;
            }
            if (cs[j] != '.') {
                return false;
            }
            cnt++;
        }
        return cnt == 3 && cs[0] != '.' && cs[n - 1] != '.';
    }
    
    private boolean checkIpv6(String ip){
        int n = ip.length(),cnt = 0;
        char[] cs = ip.toCharArray();
        for(int i = 0; i < n && cnt <= 7;){
            int j = i;
            while (j < n && ((cs[j] >= 'a' && cs[j] <= 'f') || (cs[j] >= 'A' && cs[j] <= 'F') || (cs[j] >= '0' && cs[j] <= '9'))) {
                j++;
            }
            if(i == j || j - i > 4){
                return false;
            }
            i = j + 1;
            if (j == n) {
                continue;
            }
            if (cs[j] != ':') {
                return false;
            }
            cnt++;
        }
        return cnt == 7 && cs[0] != ':' && cs[n - 1] != ':';
    }
    
    public static void main(String[] args) {
        validIPAddress validIPAddress = new validIPAddress();
        String queryIP = "172.16.254.1";
        System.out.println(validIPAddress.validIPAddress(queryIP));
    }
}
